<template>
  <el-upload
    v-bind="$attrs"
    :action="action"
    :list-type="listType"
    :multiple="multiple"
    :accept="accept"
    :limit="limit"
    :file-list="fileList"
    :disabled="disabled"
    :auto-upload="autoUpload"
    :show-file-list="showFileList"
    @change="handleChange"
    @success="handleSuccess"
    @error="handleError"
    @exceed="handleExceed"
  >
    <template v-if="listType === 'picture-card'">
      <el-icon><Plus /></el-icon>
    </template>
    <template v-else>
      <el-button type="primary">
        <el-icon><Upload /></el-icon>
        上传文件
      </el-button>
      <div slot="tip" class="el-upload__tip" v-if="tip">
        {{ tip }}
      </div>
    </template>
  </el-upload>
</template>

<script setup>
import { computed, ref } from 'vue'
import { ElUpload, ElButton, ElIcon } from 'element-plus'
import { Plus, Upload } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: [String, Array],
  action: {
    type: String,
    default: ''
  },
  listType: {
    type: String,
    default: 'text'
  },
  multiple: Boolean,
  accept: String,
  limit: Number,
  disabled: Boolean,
  autoUpload: {
    type: Boolean,
    default: true
  },
  showFileList: {
    type: Boolean,
    default: true
  },
  tip: String
})

const emit = defineEmits(['update:modelValue', 'change', 'success', 'error', 'exceed'])

const fileList = computed(() => {
  if (!props.modelValue) return []
  
  if (Array.isArray(props.modelValue)) {
    return props.modelValue.map((file, index) => ({
      name: file.name || `file_${index}`,
      url: file.url || file,
      uid: file.uid || index
    }))
  }
  
  return [{
    name: 'file',
    url: props.modelValue,
    uid: 1
  }]
})

const handleChange = (file, fileList) => {
  const value = props.multiple ? fileList : (fileList[0] || null)
  emit('update:modelValue', value)
  emit('change', file, fileList)
}

const handleSuccess = (response, file, fileList) => {
  emit('success', response, file, fileList)
}

const handleError = (error, file, fileList) => {
  emit('error', error, file, fileList)
}

const handleExceed = (files, fileList) => {
  emit('exceed', files, fileList)
}
</script>